<template>
  <div class="search-container">
    <!-- 顶部导航栏 -->
    <van-nav-bar left-arrow @click-left="onClickLeft" :fixed="true" :placeholder="true">
      <template #title>
        <van-search
          v-model="keyboard"
          clearable
          clear-trigger="always"
          class="custom-search"
          left-icon=""
          :placeholder="hotSearchList[0]?.keyword"
          @clear="clear"
        />
      </template>
      <template #right>
        <span class="search-btn" v-if="isShow" @click="onSearch(keyboard)">搜索</span>
      </template>
    </van-nav-bar>

    <!-- 热门搜索 -->
    <div class="hot-search" v-if="searchHintList.length === 0 && searchResultList.length === 0">
      <div class="hot-search-title">热门搜索</div>
      <div class="hot-search-tags">
        <template v-for="(item, index) in hotSearchList" :key="index">
          <van-tag round class="tag" @click="onSearch(item.keyword)">
            {{ item.keyword }}
          </van-tag>
        </template>
      </div>
    </div>

    <!-- 搜索推荐列表 -->
    <div class="hint-list" v-if="searchHintList.length > 0">
      <template v-for="(searchHint, outerIndex) in searchHintList" :key="outerIndex">
        <template v-for="(item, innerIndex) in searchHint" :key="innerIndex">
          <template v-if="item.hintType === 'STAR_TOUR'">
            <div class="hint-item star_tour" @click="handleHintClick(item.id)">
              <div class="symbol">巡演</div>
              <div class="title">{{ item.name }}</div>
            </div>
          </template>

          <template v-if="item.hintType === 'SHOW'">
            <div class="hint-item show" @click="handleHintClick(item.id)">
              <div class="left">
                <div class="header">
                  <div class="city">{{ item.showCity }}</div>

                  <div class="title">{{ item.name }}</div>
                </div>

                <div class="date">{{ item.showDate }}</div>

                <div class="venue">{{ item.venueName }}</div>
              </div>
              <div class="right">
                <span class="prefix">{{ showItem.priceInfo?.prefix }}</span>
                {{ showItem.priceInfo?.yuanNum }}
                <span class="suffix">{{ showItem.priceInfo?.suffix }}</span>
              </div>
            </div>
          </template>
        </template>
      </template>
    </div>

    <!-- 搜索结果列表 -->
    <div class="result-list" v-if="searchResultList.length > 0">
      <ul class="category-list">
        <li
          class="category-item"
          v-for="result in searchResultList"
          :key="result.showId"
          @click="goToDetail(result.showId)"
        >
          <div class="left">
            <img :src="result.imgUrl" class="thumb" />
          </div>

          <div class="right">
            <div class="show-title">
              <div class="title">
                <span class="city">{{ result.showCity }}</span
                >{{ result.showName }}
              </div>
            </div>

            <div class="show-date">
              {{ result.showDate }}
            </div>

            <div class="show-venue">
              {{ result.venueName }}
            </div>
            <div class="show-tags">
              <template v-for="tag in result.tags" :key="tag.tagId">
                <van-tag round class="tag" @click="clickTag(tag)">#{{ tag.tagName }}</van-tag>
              </template>
            </div>

            <div class="show-price">
              <span class="prefix">{{ result.priceInfo?.prefix }}</span>
              {{ result.priceInfo?.yuanNum }}
              <span class="suffix">{{ result.priceInfo?.suffix }}</span>
            </div>
            <div class="status">{{ result.showStatusDisplayName }}</div>
            <div class="note">{{ result.showSupplierNote }}</div>
          </div>
        </li>
      </ul>
    </div>

    <!-- 为你推荐 -->
    <div class="recommends" v-if="searchRecommendList.length > 0">
      <div class="recommends-title">为你推荐</div>
      <ul class="recommends-list">
        <li
          class="recommends-list-item"
          v-for="recommend in searchRecommendList"
          :key="recommend.showId"
        >
          <div class="cover">
            <img :src="recommend.imgUrl" class="thumb" />
            <div class="tag"></div>
          </div>

          <div class="city-title">
            <div class="title">
              <span class="city">{{ recommend.showCity }}</span
              >{{ recommend.showName }}
            </div>
          </div>

          <div class="time">{{ recommend.showDate }}</div>

          <div class="status">{{ recommend.showStatusDisplayName }}</div>

          <div class="price">
            {{ recommend.priceInfo?.prefix }} <span>{{ recommend.priceInfo?.yuanNum }}</span>
            {{ recommend.priceInfo?.suffix }}
          </div>
          <div class="note">{{ recommend.showSupplierNote }}</div>
        </li>
      </ul>
    </div>
  </div>
</template>

<script setup>
import { formatSearchHintList } from '@/tool/index.js'
import { ref, onMounted, watch, computed } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()

import { fetchHotSearch, fetchSearchList, fetchSearchHint } from '@/api/index.js'
import { useStore } from '@/stores/index.js'
const store = useStore()

// 搜索关键词
const keyboard = ref('')

const isShow = ref(true)

const pageNum = ref(1)
const length = ref(10)
const offset = computed(() => (pageNum.value - 1) * length.value)

// 热门搜索列表
const hotSearchList = ref([])

// 搜索推荐列表
const searchHintList = ref([])

// 搜索结果
const searchResultList = ref([])
// 为你推荐
const searchRecommendList = ref([])

const isManualSearch = ref(false)

// 加载状态
const loading = ref(false)

//价格格式化
const formatPrice = (priceInfo) => {
  if (priceInfo && priceInfo.yuanNum && priceInfo.centNum && priceInfo.suffix && priceInfo.prefix) {
    return priceInfo.prefix + priceInfo.yuanNum + '.' + priceInfo.centNum + priceInfo.suffix
  } else {
    return ''
  }
}

// 返回按钮点击事件
const onClickLeft = () => {
  router.back(-1)
}

// 点击热门搜索
// const handleHotSearch = (keyword) => {
//   isManualSearch.value = true  // 阻止自动触发 performHints
//   keyboard.value = keyword
//   performSearch(keyword)
// }

// 点击搜索按钮
const onSearch = (keyword) => {
  isManualSearch.value = true // 阻止自动触发 performHints
  keyboard.value = keyword
  searchHintList.value = []
  performSearch(keyword)

  // 隐藏搜索按钮 当前输入框为空 或者点 清理按钮 按钮再出现

  isShow.value = false
}

//获取搜索推荐
const performHints = async (keyword) => {
  // 防止 keyword 为 null/undefined
  if (!keyword || typeof keyword !== 'string') return

  const searchKeyword = keyword.trim()
  if (!searchKeyword) return // 空字符串也不执行搜索

  loading.value = true
  try {
    pageNum.value = 1
    await getHintList(store.currentCity.cityId, searchKeyword)
  } catch (error) {
    console.error('搜索失败:', error)
  } finally {
    loading.value = false
  }
}

// 执行搜索
const performSearch = async (keyword) => {
  // 防止 keyword 为 null/undefined
  if (!keyword || typeof keyword !== 'string') return

  const searchKeyword = keyword.trim()
  if (!searchKeyword) return // 空字符串也不执行搜索

  loading.value = true
  try {
    pageNum.value = 1
    await getSearchList(store.currentCity.cityId, searchKeyword, length.value, offset.value)
  } catch (error) {
    console.error('搜索失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取搜索推荐方法
const getHintList = async (cityId, keyword) => {
  try {
    const { statusCode, data } = await fetchSearchHint(cityId, keyword)
    if (statusCode == 200) {
      searchHintList.value = formatSearchHintList(data)
    }
  } catch (error) {
    console.log('获取搜索推荐失败:', error)
  }
}

// 获取搜索列表方法
const getSearchList = async (cityId, keyword, length, offset) => {
  const {
    statusCode,
    data: { recommend, searchData },
  } = await fetchSearchList(cityId, keyword, length, offset)

  if (statusCode === 200) {
    // console.log('searchData', searchData)
    if (searchData.length > 0) {
      // 搜索结果列表
      searchResultList.value = searchData
    }

    if (recommend.length > 0) {
      // 搜索推荐列表
      searchRecommendList.value = recommend
    }

    // console.log('recommend', recommend)
  }
}

// 获取热门搜索方法
const getHotSearch = async (cityId) => {
  try {
    const {
      statusCode,
      data: { hotKeywords },
    } = await fetchHotSearch(cityId)
    if (statusCode === 200) {
      if (hotKeywords.length > 0) {
        hotSearchList.value = hotKeywords
      }
    }
  } catch (error) {
    console.log('获取热门搜索词错误', error)
  }
}

// 监听键盘输入变化
watch(keyboard, (newVal) => {
  if (newVal.length >= 1 && !isManualSearch.value) {
    //搜索词推荐
    performHints(newVal)
  }
  if (newVal.length === 0) {
    searchHintList.value = []
  }
  isManualSearch.value = false
})

// 页面加载时初始化
onMounted(() => {
  // 获取热门搜索
  getHotSearch(store.currentCity.cityId)
})

// 清空
const clear = () => {
  // 清空搜索框
  keyboard.value = ''

  // 清空搜索推荐
  searchHintList.value = []
  // 清空搜索结果列表
  searchResultList.value = []

  //清空为你推荐
  searchRecommendList.value = []
}

//进入详情页
const goToDetail = (id) => {
  router.push({ path: '/show-detail', query: { showId: id } })
}
</script>

<style scoped lang="scss">
.search-container {
  min-height: 100vh;
  background-color: #fff;

  span.search-btn.none {
    display: none;
  }

  .hot-search {
    padding: 15px;
    background-color: #fff;

    .hot-search-title {
      font-size: 14px;
      color: #666;
      margin-bottom: 10px;
    }

    .hot-search-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
      align-items: center;
      justify-content: flex-start;

      .tag {
        font-size: 14px;
        border-color: #ddd;
        background-color: #f5f5f5;
        color: #323038;
        padding: 8px 18px;

        &:hover {
          background-color: #ebebeb;
        }
      }
    }
  }

  .hint-list {
    padding: 10px 15px;
    display: flex;
    flex-direction: column;

    .hint-item.star_tour {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      gap: 10px;
      border-bottom: 1px solid #eaeaea;
      padding: 15px 0;

      .symbol {
        flex: 0 0 auto;
        color: rgb(255, 29, 65);
        border: 1px solid rgb(255, 29, 65);
        padding: 2px;
        border-radius: 4px;
        font-size: 10px;
        font-weight: 600;
      }

      .title {
        flex: 1;
        font-size: 14px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: wrap;
        word-break: break-all;
        width: 100%;
      }
    }

    .hint-item.show {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      gap: 10px;
      border-bottom: 1px solid #eaeaea;
      padding: 15px 0;

      .left {
        flex: 1;
        display: flex;
        flex-direction: column;
        align-items: flex-start;
        justify-content: space-between;

        gap: 5px;

        .header {
          display: flex;
          align-items: center;
          justify-content: flex-start;
          gap: 10px;

          .city {
            flex: 0 0 auto;
            border: 1px solid rgba(0, 0, 0, 0.51);
            padding: 2px;
            border-radius: 4px;
            font-size: 10px;
            font-weight: 600;
          }

          .title {
            flex: 1;
            font-size: 14px;
            font-weight: 500;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            word-break: break-all;
            width: 100%;
          }
        }

        .date {
          font-size: 12px;
          color: #95949d;
          font-weight: 400;
          margin: 3px 0;
        }

        .venue {
          font-size: 12px;
          color: #95949d;
          font-weight: 400;
        }
      }

      .right {
        flex: 0 0 auto;
      }
    }
  }

  .result-list {
    // padding: 0 0 15px;
    // border-bottom: 1px solid #EAEAEA;

    .category-list {
      list-style: none;
      display: flex;
      flex-direction: column;
      gap: 30px;

      padding: 20px 15px 30px 15px;

      .category-item {
        display: flex;
        align-items: flex-start;
        justify-content: flex-start;
        gap: 15px;

        .left {
          width: 100px;
          height: 150px;
          overflow: hidden;
          flex-shrink: 0;

          .thumb {
            width: 100%;
            height: 100%;
            object-fit: cover;
            object-position: center;
            display: block;
            border-radius: 6px;
          }
        }

        .right {
          // height: 150px;
          display: flex;
          flex-direction: column;
          align-items: flex-start;
          justify-content: space-between;
          gap: 5px;

          /* 占据剩余空间 */
          .show-title {
            display: flex;
            align-items: flex-start;
            justify-content: flex-start;

            .title {
              color: #000;
              font-size: 16px;
              font-weight: 700;
              display: -webkit-box;
              -webkit-line-clamp: 2;
              -webkit-box-orient: vertical;
              overflow: hidden;
              text-overflow: ellipsis;
              word-wrap: break-word;
              word-break: break-all;

              .city {
                color: #000;
                font-size: 10px;
                font-weight: 600;
                border: 1px solid rgba(0, 0, 0, 0.25);
                margin-right: 5px;
                padding: 2px;
              }
            }
          }

          .show-date {
            font-size: 14px;
            font-weight: 500;
          }

          .show-venue {
            font-size: 14px;
            font-weight: 400;
          }

          .show-tags {
            display: flex;
            align-items: center;
            gap: 10px;

            .tag {
              flex: 0 0 auto;
              background: #f5f5f5;
              color: #323038;
              font-size: 10px;
              font-weight: 500;
              padding: 4px 6px;
            }
          }

          .show-price {
            color: #ff1d41;
            font-size: 20px;
            letter-spacing: -1px;

            .prefix {
              font-size: 10px;
            }

            .suffix {
              font-size: 10px;
            }
          }

          .status {
            color: #323038;
            font-size: 12px;
            border: 1px solid #97979780;
            border-radius: 4px;
            padding: 2px;
            margin: 5px 0 0;
          }

          .note {
            color: #95949d;
            font-size: 10px;
            margin: 5px 0 0;
          }
        }
      }

      .category-item:last-child {
        border-bottom: 1px solid #eaeaea;
        padding-bottom: 20px;
      }
    }
  }

  .recommends {
    padding: 0 15px;

    .recommends-title {
      font-size: 18px;
      font-weight: 600;
      margin-bottom: 10px;
    }

    .recommends-list {
      list-style: none;
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      grid-gap: 20px;
      align-items: start;
      justify-items: start;
      justify-content: start;
      align-content: center;

      li.recommends-list-item {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: flex-start;
        gap: 10px;
        width: 100%;
        overflow: hidden;
        padding: 0 0 5px;

        .cover {
          height: 250px;
          width: 100%;
          position: relative;
          margin-bottom: 10px;

          .thumb {
            width: 100%;
            height: 100%;
            object-fit: cover;
            border-radius: 6px;
          }

          .tag {
          }
        }

        .city-title {
          display: flex;
          align-items: flex-start;
          justify-content: flex-start;
          font-weight: 500;

          .title {
            font-size: 14px;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
            text-overflow: ellipsis;
            word-wrap: break-word;
            word-break: break-all;

            .city {
              font-size: 12px;
              border: 1px solid #ccc;
              margin-right: 5px;
              padding: 2px;
            }
          }
        }

        .time {
          width: 100%;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          font-size: 12px;
          font-weight: 500;
          color: #323038;
          margin: 0;
        }

        .status {
          color: #323038;
          font-size: 12px;
          border: 1px solid #97979780;
          border-radius: 4px;
          padding: 2px;
          margin: 0;
        }

        .price {
          color: #ff1d41;
          width: 100%;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          font-size: 10px;
          font-weight: 400;

          span {
            font-size: 20px;
            font-weight: 700;
          }
        }

        .note {
          color: #95949d;
          font-size: 10px;
          margin: 5px 0 0;
        }
      }
    }
  }
}

///////////////////////////////

.search-results {
  padding: 15px;
  background-color: #fff;

  .no-results {
    text-align: center;
    padding: 40px 0;

    .van-icon {
      color: #ccc;
      margin-bottom: 10px;
    }

    p {
      color: #999;
      font-size: 14px;
    }
  }

  .results-list {
    .result-item {
      padding: 15px 0;
      border-bottom: 1px solid #eee;

      &:last-child {
        border-bottom: none;
      }

      .result-title {
        font-size: 16px;
        color: #333;
        margin-bottom: 5px;
      }

      .result-desc {
        font-size: 14px;
        color: #666;
      }
    }
  }

  .loading {
    text-align: center;
    padding: 40px 0;
  }
}

:deep(.van-nav-bar__title) {
  font-size: 16px;
  color: #333;
  line-height: 1.5;
  max-width: 100%;
}

:deep(.van-nav-bar__right) {
  font-size: 16px;
  color: #ff1d41;
  font-weight: bold;
}

// 自定义 van-search 样式
:deep(.van-search) {
  width: 100%; // 设置宽度为 100%
  border-radius: 20px; // 设置圆角
  background-color: #f7f8fa; // 设置背景色
  padding: 0 15px; // 添加内边距
  // box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); // 添加阴影效果（可选）
}

:deep(.van-search__content) {
  border-radius: 20px; // 确保内容区域也有圆角
  background-color: #f7f8fa;
}

:deep(.van-search__input) {
  padding: 10px 15px; // 调整输入框内边距
  font-size: 16px; // 调整字体大小
  color: #333;
  border: none; // 移除边框
}

:deep(.van-search__left-icon) {
  margin-right: 10px; // 调整左侧图标的间距
}

:deep(.van-search__right-icon) {
  margin-left: 10px; // 调整右侧图标的间距
}

:deep(.van-nav-bar .van-icon) {
  color: #c8c9cc;
}
</style>
